package com.silentfish.zweb.shiro;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.authz.UnauthenticatedException;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.stereotype.Service;

import java.util.HashSet;

/**
 * 自定义shiro域
 */
@Service("systemAuthorizingRealm")
public class SystemAuthorizingRealm extends AuthorizingRealm implements InitializingBean{

    /**
     * 返回用户的认证信息
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {

        String username = (String) token.getPrincipal();//UsernamePasswordToken的getPrincipal和getUsername是一致的

        Object user = new Object();//findByName 根据Principal表示查询用户信息

        if(user == null){//找不到用户直接返回异常
            throw new UnauthenticatedException();
        }

        String password = "";//user.getPassword().substring(0,16)
        byte[] salt = new byte[1];//Encodes.decodeHex(password)
        return new SimpleAuthenticationInfo(username, password, ByteSource.Util.bytes(salt), getName());//返回密码及盐用于验证
    }

    /**
     * 返回用户的权限信息
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {

        String username = (String) principals.getPrimaryPrincipal();

        //根据username获取角色或权限信息

        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        info.addRoles(new HashSet<String>());               //返回角色信息
        info.addStringPermissions(new HashSet<String>());   //返回权限信息
        return info;
    }

    /**
     * 设置校验的规则 (在bean初始化完成以后)
     */
    public void afterPropertiesSet() {
        //HashedCredentialsMatcher中的doCredentialsMatch方法会对比token和info的Credential(即密码)
        HashedCredentialsMatcher matcher = new HashedCredentialsMatcher("MD5");//加密算法为md5
        matcher.setHashIterations(2);//2次md5迭代
        setCredentialsMatcher(matcher);
    }
//
//    /**
//     * 自定义
//     */
//    public static class Principal implements Serializable {
//
//        private static final long serialVersionUID = 1889121397360659511L;
//
//        private String id;              //编号
//        private String loginName;       //登录名
//        private String name;            //姓名
//
//
//        public Principal(User user) {
//            this.id = user.getId();
//            this.loginName = user.getLoginName();
//            this.name = user.getName();
//        }
//
//        public String getId() {
//            return id;
//        }
//
//        public String getLoginName() {
//            return loginName;
//        }
//
//        public String getName() {
//            return name;
//        }
//
//
//        /**
//         * 获取SESSIONID
//         */
//        public String getSessionid() {
//            try{
//                return (String) UserUtils.getSession().getId();
//            }catch (Exception e) {
//                return "";
//            }
//        }
//
//        @Override
//        public String toString() {
//            return id;
//        }
//
//    }

//    public String encryptionPassword(String plainPassword){
//        byte[] salt = Digests.generateSalt(SALT_SIZE);  //SALT_SIZE=8
//        byte[] hashPassword = Digests.sha1(plainPassword.getBytes(), salt, HASH_INTERATIONS);  //HASH_INTERATIONS=1024
//        return Encodes.encodeHex(salt)+Encodes.encodeHex(hashPassword);
//    }
}